package com.ianmoone.lintcode;

public class FindLongetString {
	public static int getAns(String S) {
        // Write your code here
        int l = S.length();
        int[] numA = new int[l+1];
        int[] numB = new int[l+1];
        int a = 0, b = 0;
        
        for(int i = 0; i < l; i++) {
            if(S.charAt(i) == 'A') a++;
            else b++;
            numA[i+1] = a;
            numB[i+1] = b;
        }
        
        if(a == 0 || b == 0) return 0;
        
        int res = a < b? a : b;
        for(res *= 2; res > 0; res -= 2) {
            for(int i = res; i < l+1; i++) {
                if(numA[i] - numA[i-res]== numB[i] - numB[i-res]) {
                    return res;
                }
            }
        }
        
        return 0;
    }
	public static void main(String[] args) {
		String teString = "ABAAABBBAAAA";
		getAns(teString);
	}

}
